<template>
  <div class="home-container">
    <!-- 顶部导航栏 -->
    <TopNavBar> </TopNavBar>

    <!-- 首页主体 -->
    <van-pull-refresh
      class="pull-container"
      v-model="refreshing"
      @refresh="onRefresh"
      pulling-text="下拉即可刷新..."
      loosing-text="释放即可刷新..."
      loading-text="加载中..."
      success-text="刷新成功"
    >
      <van-list
        class="car-box"
        v-model:loading="loading"
        v-model:error="error"
        @load="onLoad"
        :finished="finished"
        finished-text="没有更多了"
        error-text="请求失败，点击重新加载"
      >
        <van-cell
          class="car-item"
          center
          v-for="item in list"
          :key="item.id"
          @click="handleConnect(item.id)"
          :title="item.ip"
        >
          <template #icon>
            <SvgIcon icon-class="home-car" />
          </template>
          <template #right-icon>
            <van-tag type="warning" v-if="item.connectStatus === 0">未连接</van-tag>
            <van-tag type="success" v-else-if="item.connectStatus === 1">连接成功</van-tag>
            <van-tag type="danger" v-else-if="item.connectStatus === 2">连接失败</van-tag>
          </template>
        </van-cell>

        <!-- 空数据占位 -->
        <template v-if="!list.length && !loading && !error">
          <van-empty description="暂无车辆数据" />
        </template>

        <!-- 返回顶部 -->
        <van-back-top offset="200" bottom="54px" right="30px" />
      </van-list>
    </van-pull-refresh>

    <!-- 底部tab栏 -->
    <BottomTabBar></BottomTabBar>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { carListApi } from '@/apis/car'
import type { ICarResponse } from '@/types/apis/car'

// 路由器实例
const router = useRouter()

// 列表
const list = ref<ICarResponse[]>([])
// 触底加载状态
const loading = ref(false)
// 数据全部加载完成
const finished = ref(false)
// 列表请求失败
const error = ref(false)
// 刷新状态
const refreshing = ref(false)

const pageNum = ref(1)
const pageSize = 10

/**
 * 触底加载
 */
const onLoad = async () => {
  loading.value = true
  error.value = false

  try {
    const res = await carListApi({ pageNum: pageNum.value, pageSize })

    // 刷新时清空列表
    if (refreshing.value) {
      list.value = []
      refreshing.value = false
      pageNum.value = 1
    }

    // 拼接新数据
    // list.value = [...list.value, ...res.list]

    // 拼接新数据前先给每项添加连接状态
    const dataWithStatus = res.list.map((item) => ({
      ...item,
      connectStatus: 0, // 0:未连接，1:成功，2:失败
    }))

    list.value = [...list.value, ...dataWithStatus]

    // 判断是否加载完毕
    if (list.value.length >= res.total) {
      finished.value = true
    } else {
      finished.value = false
      pageNum.value++
    }

    loading.value = false
  } catch (e) {
    console.log(e)
    loading.value = false
    error.value = true
  }
}

/**
 * 下拉刷新
 */
const onRefresh = () => {
  finished.value = false
  pageNum.value = 1
  loading.value = true
  onLoad()
}

/**
 * 连接车辆
 * @param id 车辆id
 */
const handleConnect = (id: number | string) => {
  const target = list.value.find((item) => item.id === id)
  if (!target) return

  // 模拟连接成功
  target.connectStatus = 1

  // 请求连接车辆，成功后将车辆信息保存在本地存储中
  console.log(id)

  showSuccessToast('连接成功')

  // 跳转到driver页面
  router.push({ name: 'drive', query: { id } })
}
</script>

<style lang="scss" scoped>
.home-container {
  height: 100vh;
  padding-top: var(--van-nav-bar-height);
  display: flex;
  flex-direction: column;

  .pull-container {
    flex: 1;
    overflow-y: auto; // 让它成为滚动容器

    .car-box {
      padding-bottom: calc(var(--van-tabbar-height) + 100px); // 解决 bottom 遮挡
    }
  }
}
</style>
